package com.server.server_a10.management.controller;

import com.server.server_a10.entity.Home;
import com.server.server_a10.management.entity.ManageInf;
import com.server.server_a10.mapper.HomeMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class manageHomeHandle {
    @Autowired
    HomeMapper homeMapper;

    @GetMapping(value = "/adminGetHome")
    public ManageInf adminShowUser(@RequestParam("limit") int limit,
                                   @RequestParam("page") int page,
                                   @RequestParam("name") Object n) {
        ManageInf inform = new ManageInf();

        String name = (String) n;

        int index = (page - 1) * limit;

        List<Home> homes;
        if (name.isEmpty() || name.equals("\"\"")) {
            name = "";
        }

        homes = homeMapper.getHomeLimit(index, limit, name);
        int count = homeMapper.getHomeCount();
        inform.setCount(count);
        if (homes.isEmpty()) {
            inform.isNull("似乎没有任何数据");
        } else {
            inform.success("信息加载成功", homes);
        }
        return inform;
    }

    @PostMapping(value = "/adminDelHome")
    public ManageInf adminDelHome(@RequestBody Map<String,Object> request){
        int id = (int) request.get("id");

        ManageInf inform = new ManageInf();

        int isOk = 0;
        try{
            isOk = homeMapper.delHomeById(id);
        }catch (Exception e){
            inform.fail("该操作失败");
        }

        if (isOk<=0){
            inform.isNull("没有该房子");
        }else {
            inform.success("操作成功",null);
        }

        return inform;
    }

    @PostMapping(value = "/adminAddHome")
    public ManageInf adminAddHome(@RequestBody Map<String,Object> request){
        ManageInf inform = new ManageInf();
        String name = (String) request.get("name");
        int master_id = (int) request.get("masterId");
        String address = (String) request.get("address");

        int isOk = 0;
        try {
            isOk = homeMapper.insHome(name,master_id,address);
        }catch (Exception e){
            inform.fail("数据库错误");
        }
        if(isOk<=0) {
            inform.isNull("创建失败");
        }else {
            inform.success("创建成功",null);
        }

        return inform;
    }

}
